package org.water.garden.view;

import org.water.garden.R;

import android.content.Context;
import android.database.Cursor;
import android.provider.Im;
import android.provider.Im.Chats;
import android.provider.Im.Contacts;
import android.provider.Im.Messages;
import android.view.View;
import android.widget.ResourceCursorAdapter;
import android.widget.TextView;

public class ChatListAdapter extends ResourceCursorAdapter {

	public ChatListAdapter(Context context, Cursor c) {
		super(context, R.layout.chat_list_row, c);
	}

	@Override
	public void bindView(View view, Context context, Cursor cursor) {
		//Account name text view
		Integer contactId = cursor.getInt(cursor.getColumnIndex(Chats.CONTACT_ID));

		Cursor cCursor = Contacts.query(context.getContentResolver(), new String[] { 
			Contacts._ID, Contacts.NICKNAME, Contacts.USERNAME, Contacts.PROVIDER,
			Contacts.ACCOUNT }, "contacts._id = " + contactId, null);

		if (cCursor.first()) {

			StringBuilder sb = new StringBuilder();
			sb.append(Messages.ACCOUNT).append("=? AND ");
			sb.append(Messages.SHOW_TIME_STAMP).append(" is NULL AND ");
			sb.append(Messages.CONTACT).append("=?");
			
			Cursor mcursor = context.getContentResolver().query(Im.Messages.CONTENT_URI, new String[] { 
					Messages._ID, Messages.BODY, Messages.SHOW_TIME_STAMP
					}, sb.toString(),
					new String[] { Integer.toString(cCursor.getInt(4)), cCursor.getString(2) }, null);
			
			((TextView)view.findViewById(android.R.id.text1)).setText("与 " + cCursor.getString(1) + " 聊天");

			if(mcursor.first()){
				((TextView)view.findViewById(android.R.id.text2)).setText("共" + mcursor.count() + "条新消息.");
			} else {
				((TextView)view.findViewById(android.R.id.text2)).setText("没有新消息.");
			}
		}
	}
}